package com.springcloud.security;

import com.springcloud.commons.result.Result;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的失败处理类
 */
@Component
public class MyFailureHandler extends SimpleUrlAuthenticationFailureHandler {

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                            AuthenticationException exception) throws IOException {
            response.setContentType("text/html;charset=UTF-8");
            Result result = new Result();
            result.setMsg("用户名或密码错误");
            result.setCode(400);
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(result);
            response.getWriter().write(data);

        }
}
